package com.topboya.linker.ui.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.topboya.linker.R;
import com.topboya.linker.model.response.FeekbackReponse;
import com.topboya.linker.model.response.HomeListResponse;
import com.topboya.linker.model.response.TaskResponse;
import com.topboya.linker.ui.adapter.FeedBackAdapter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.presenter.FeekbackPresenter;
import com.topboya.linker.ui.view.FeekbackView;
import com.topboya.linker.utils.AndroidUtils;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

public class FeedbackAndDetailActitivy extends BaseActivity<FeekbackView,FeekbackPresenter> implements FeekbackView,TencentLocationListener {

    private static final String TAG = "FeedbackAndDetailActitiy:";
    private Toolbar toolbar;
    private TextView toolbar_title;
    private HomeListResponse.TaskList task;
    private LinearLayout ll_root;
    private TextView tv_device_name;
    private TextView tv_sustomer_name;
    private TextView tv_task_type;
    private TextView tv_product_name;
    private TextView tv_file_name;
    private TextView tv_follow_user_name;
    private TextView tv_taskdescribe_title;
    private EditText et_task_feekback;
    private RelativeLayout rl_product;
    private RelativeLayout rl_file;
    private RecyclerView ry_visitor_result;
    private TextView tv_start_time_day;
    private TextView tv_start_time_hour;
    private TextView tv_end_time_day;
    private TextView tv_end_time_hour;
    private TextView tv_toolbar_right;
    private ArrayList<String> feekbacknamelist;
    private List<FeekbackReponse.FeekbackData> data;
//    private TagAdapter flowdepTagAdapter;
    private FeedBackAdapter feekbackAdapter;
    private String orgID;
    private String taskid;
    private String feekbackid;
    private ScrollView scroll;
//    判断是任务反馈页面还是是任务详情页面，任务反馈页面就显示
    private boolean isfeedback =true;
//    任务反馈页面和任务详情页面
    @Override
    protected int getLayoutId() {

        return R.layout.activity_feekback_detail;
    }

    @Override
    protected void initView() {

        ll_root = findViewById(R.id.ll_root);
        scroll = findViewById(R.id.scroll);
        toolbar_title = findViewById(R.id.toolbar_title);
        tv_device_name = findViewById(R.id.tv_device_name);
        tv_sustomer_name = findViewById(R.id.tv_sustomer_name);
        tv_task_type = findViewById(R.id.tv_task_type);
        tv_product_name = findViewById(R.id.tv_product_name);
        tv_file_name = findViewById(R.id.tv_file_name);
        tv_follow_user_name = findViewById(R.id.tv_follow_user_name);
        et_task_feekback =findViewById(R.id.et_task_feekback);
        ry_visitor_result =findViewById(R.id.ry_visitor_result);
        rl_product =findViewById(R.id.rl_product);
        rl_file =findViewById(R.id.rl_file);
        tv_taskdescribe_title =findViewById(R.id.tv_taskdescribe_title);
        tv_start_time_day =findViewById(R.id.tv_start_time_day);
        tv_start_time_hour =findViewById(R.id.tv_start_time_hour);
        tv_end_time_hour =findViewById(R.id.tv_end_time_hour);
        tv_end_time_day =findViewById(R.id.tv_end_time_day);
        tv_toolbar_right =findViewById(R.id.tv_toolbar_right);
        toolbar =findViewById(R.id.toolbar);
    }


    @Override
    protected void initData() {

        isfeedback = getIntent().getBooleanExtra("isfeedback",true);
        task = (HomeListResponse.TaskList) getIntent().getSerializableExtra("taskLists");

        tv_device_name.setText(task.getOrgName());
        tv_sustomer_name.setText(task.getCusName());
        tv_task_type.setText(task.getVisitType());
        if (null !=task.getFollowUserName()){

            tv_follow_user_name.setText(task.getFollowUserName());
        }
        taskid = task.getId();
        orgID = task.getOrgId();
        setProductAndFile();
//        设置是签到任务反馈还是任务详情任务反馈
        if (isfeedback){
            toolbar_title.setText("反馈任务");
            setFeedbackContent();
            et_task_feekback.setVisibility(View.VISIBLE);
        }else {

            toolbar_title.setText("任务详情");
            ry_visitor_result.setVisibility(View.GONE);
            et_task_feekback.setVisibility(View.GONE);
            tv_toolbar_right.setVisibility(View.GONE);

        }
        mPresenter.getTask(taskid);

    }

    private void setFeedbackContent() {
        data = new ArrayList<>();
        mPresenter.getFeekbackLable("feekback");
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 5);
//        flowdepTagAdapter = new FlowdepTagAdapter(this,tagflow_task_feekback,feekbacknamelist);
        ry_visitor_result.setLayoutManager(layoutManager);
        feekbackAdapter = new FeedBackAdapter(this,data);
        ry_visitor_result.setAdapter(feekbackAdapter);

    }

    private void setProductAndFile() {

        String fileNumber = task.getFileNumber();
        String productNumber = task.getProductNum();
        if (null != productNumber&& !"".equals(productNumber) && Integer.parseInt(productNumber) ==1){
//            表示只有一个产品,只显示名称就可以
            tv_product_name.setVisibility(View.VISIBLE);
            tv_product_name.setText(task.getProductName());

        }else {

            tv_product_name.setVisibility(View.VISIBLE);
            tv_product_name.setText(productNumber);
        }

        if (null != fileNumber && !"".equals(fileNumber) && Integer.parseInt(fileNumber) ==1){
//            表示只有一个产品,只显示名称就可以
            tv_file_name.setVisibility(View.VISIBLE);
            tv_file_name.setText(task.getProductName());

        }else {

            tv_file_name.setVisibility(View.VISIBLE);
            tv_file_name.setText(fileNumber);
        }

    }
    /**
     * 使ScrollView指向底部
     */
    private void changeScrollView(){

        h.postDelayed(() -> scroll.scrollTo(0, scroll.getHeight()+100), 300);
    }

    Handler h = new Handler(){
        public void handleMessage(Message msg) {
        };
    };
    @Override
    protected void initListener() {
        toolbar.setNavigationOnClickListener(v -> finish());
        tv_toolbar_right.setOnClickListener(v -> {

            getLocationFromTencent();
        });
        et_task_feekback.setOnClickListener(v -> {

            changeScrollView();
        });
//        btn_feek_back.setOnClickListener(v -> {
////            反馈的时候在获取地理位置
//                getLocationFromTencent();
//        });
//        tagflow_task_feekback.setOnSelectListener(selectPosSet -> {
//
//            LogUtils.v("choose:" + selectPosSet.toString());
//            set =selectPosSet;
//
//        });
        rl_product.setOnClickListener(v -> {

            Intent  intent = new Intent(FeedbackAndDetailActitivy.this,SeeTaskProductActivity.class);
            intent.putExtra("task",task);
            intent.putExtra("istaskFile",true);
            startActivity(intent);
//            jumpToActivity(SeeTaskProductActivity.class);

        });

        rl_file.setOnClickListener(v -> {

            Intent  intent = new Intent(FeedbackAndDetailActitivy.this,SeeTaskFileActivity.class);
            intent.putExtra("task",task);
            intent.putExtra("istaskFile",true);
            startActivity(intent);

        });
    }

    @Override
    protected FeekbackPresenter createPresenter() {

        return new FeekbackPresenter(this);
    }

    @Override
    public void getFeekbackLable(List<FeekbackReponse.FeekbackData> data) {

//        成功获取到任务反馈的字典数据
         LogUtils.v(TAG + data.toString());
         this.data.clear();
         this.data.addAll(data);

         feekbackAdapter.notifyDataSetChanged();


    }


    @Override
    public void miniSignOut() {

//    反馈和签出成功的结果,调到主页
//        jumpToActivity(xMainActivity.class);
        Intent intent = new Intent(this, xMainActivity.class);
        intent.putExtra("isfeedback",true);
        startActivity(intent);
        finish();

    }

    @Override
    public void getTask(TaskResponse.Data taskdataResponse) {

        LogUtils.v(TAG+"taskdataResponse:"+taskdataResponse.toString());
        tv_start_time_day.setText(AndroidUtils.getTimeDay(taskdataResponse.getStartTime()));
        tv_start_time_hour.setText(AndroidUtils.getTimeDayHour(taskdataResponse.getStartTime()));
        tv_end_time_day.setText(AndroidUtils.getTimeDay(taskdataResponse.getEndTime()));
        tv_end_time_hour.setText(AndroidUtils.getTimeDayHour(taskdataResponse.getEndTime()));
        if (null !=taskdataResponse.getRemarks()){
            String remark = taskdataResponse.getRemarks();
            String remarks = "<font color='#000000'>任务描述：  </font><font color='#888888'>"+remark+"</font>";
            tv_taskdescribe_title.setText(Html.fromHtml(remarks));
        }

    }


    //    签到获取实时地理位置
    public void getLocationFromTencent(){

        TencentLocationRequest request = TencentLocationRequest.create();
        request.setInterval(24*60*60*1000);
        request.setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_NAME);
        request.setAllowCache(true);
        TencentLocationManager locationManager = TencentLocationManager.getInstance(this);
        int erro = locationManager.requestLocationUpdates(request, this);
        LogUtils.v(TAG+"tencent_map_error:"+erro);

    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {

        LogUtils.v(TAG + "tencentLocation"+ tencentLocation.toString());
        LogUtils.v(TAG + "latitude:"+ tencentLocation.getLatitude() +"longitude:"+ tencentLocation.getLongitude());
        String latitude = String.valueOf(tencentLocation.getLatitude());
        String longitude = String.valueOf(tencentLocation.getLongitude());
        String feektext = et_task_feekback.getText().toString().trim();
        if (feektext.isEmpty()){ UIUtils.showToast("请输入拜访结果");return;}

        ArrayList<FeekbackReponse.FeekbackData> feekbackData=  feekbackAdapter.getSelectedItem();
        if (null ==feekbackData || feekbackData.size() < 1){ UIUtils.showToast("请选择拜访结果"); return;}
        feektext = "【"+feekbackData.get(0).getLabel()+"】"+feektext;
        feekbackid = feekbackData.get(0).getId();
        LogUtils.v(TAG +"orgID:"+orgID+",feektext:"+feektext+",feekbackid:"+feekbackid+",taskid"+taskid+",latitude:"+latitude+",longitude:"+longitude);
        mPresenter.updateTaskBack(orgID,feektext,feekbackid,taskid,latitude,longitude);


    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

}
